<template>
  <div class="gl-picker dib vat">
    <div class="gl-picker-slot" @click="showPicker">
      <slot>{{title}}</slot>
    </div>
    <mt-popup v-model="show" position="bottom" class="w100">
      <div class="picker-title flex">
        <span class="flex-1"></span>
        <span class="title flex-4 tac wsnw">{{title}}</span>
        <span class="sure flex-1 tac" @click="sure">确定</span>
      </div>
      <mt-picker ref="picker" :value-key="valueKey" :slots="slots" @change="onValuesChange"></mt-picker>
    </mt-popup>
  </div>
</template>

<script>
  export default {
    name: "GlPicker",
    props: {
      options: { // 备选列表，多列时为二维数组
        type: Array,
        default() {
          return []
        },
      },
      divider: { // 分隔符，为空字符时无分隔符
        type: String,
        default: '-',
      },
      title: { // 选择picker的标题和页面上显示的默认文字
        type: String,
        default: '请选择'
      },
      valueKey: { // 选项为对象时显示的字段名称
        type: String,
        default: 'name',
      },
      value: { // 打开选择器时的默认选中的值，数组长度必须和options的长度一样，options是一维数组时长度为1
        type: Array,
        default() {
          return []
        }
      },
    },
    watch: {
      show(val) {
      },
    },
    data() {
      return {
        show: false,
        res: [],
        slots: [],
      }
    },
    methods: {
      showPicker() {
        this.slots = [];
        if (this.options.length) {
          if (this.options[0].length) {
            // 二维数组
            this.options.map((e, i) => {
              if (this.slots.length && this.divider) {
                this.slots.push({
                  divider: true,
                  content: this.divider,
                });
              }
              this.slots.push({
                flex: 1,
                values: e,
              });
            });
          } else {
            // 一维数组
            this.slots.push({
              flex: 1,
              values: this.options,
            });
          }
        }
        this.show = true;
        this.value && this.value.length && setTimeout(this.$refs.picker.setValues, 0, this.value);
      },
      sure() {
        this.$emit('sure', this.$refs.picker.getValues(), this.close);
      },
      close() {
        this.show = false;
      },
      onValuesChange(e) {
        this.res = e.getValues();
        // 选择改变时回调
        this.$emit('change', [...this.res], e);
      },
    },
  }
</script>

<style scoped lang="less">
  .gl-picker {
    .picker-title {
      line-height: 70px;
      font-size: 26px;
      color: #666;
      border-bottom: 2px #F6F7F9 solid;
      .sure {
        color: #14C8FF;
        font-size: 30px;
      }
    }
  }
</style>